//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import { Button, Card, Divider, Form, Input, List, Space, TreeSelect } from 'antd';
import { CaretDownFilled, CaretUpFilled, ReloadOutlined } from '@ant-design/icons';
import type { ISSUE_TYPE, IssueInfo } from "@/api/project_issue";
import { ISSUE_TYPE_TASK, ISSUE_TYPE_BUG, list as list_issue } from "@/api/project_issue";
import type { ENTRY_TYPE, EntryInfo } from "@/api/project_entry";
import { ENTRY_TYPE_SPRIT, ENTRY_TYPE_DOC, ENTRY_TYPE_PAGES, ENTRY_TYPE_API_COLL, list as list_entry, ENTRY_TYPE_DRAW } from "@/api/project_entry";
import { type Idea, list_idea } from "@/api/project_idea";
import { type RequirementInfo, list_requirement } from "@/api/project_requirement";
import { type CaseInfo as TestCaseInfo, list_case_flat } from "@/api/project_testcase";
import { ServerInfo, list_server } from "@/api/project_server";
import { request } from '@/utils/request';
import { get_session } from '@/api/user';
import ProjectDragTreeNode from './ProjectDragListNode';
import { NODE_TYPE_BASE_EMPTY_REF, NODE_TYPE_BASE_GROUP, NODE_TYPE_BASE_IFRAME, NODE_TYPE_BASE_TEXT, NODE_TYPE_REF_BUG, NODE_TYPE_REF_ENTRY, NODE_TYPE_REF_IDEA, NODE_TYPE_REF_REQUIREMENT, NODE_TYPE_REF_SERVER, NODE_TYPE_REF_TASK, NODE_TYPE_REF_TESTCASE } from '@/api/project_dataview';
import { issueState } from '@/utils/constant';

type TreeNodeType = "base" | "idea" | "requireMent" | "task" | "bug" | "testCase" | "server" | "workPlan" | "doc" | "draw" | "pages" | "apiColl";

const PAGE_SIZE = 10;

export interface ProjectNodeListPanelProps {
    projectId: string;
}

const ProjectNodeListPanel = (props: ProjectNodeListPanelProps) => {
    const [expand, setExpand] = useState(false);

    const [curTreeNodeType, setCurTreeNodeType] = useState<TreeNodeType>("base");
    const [totalCount, setTotalCount] = useState(0);
    const [curPage, setCurPage] = useState(0);
    const [keyword, setKeyword] = useState("");

    const [ideaList, setIdeaList] = useState<Idea[]>([]);
    const [requireMentList, setRequireMentList] = useState<RequirementInfo[]>([]);
    const [issueList, setIssueList] = useState<IssueInfo[]>([]);
    const [testCaseList, setTestCaseList] = useState<TestCaseInfo[]>([]);
    const [serverList, setServerList] = useState<ServerInfo[]>([]);
    const [entryList, setEntryList] = useState<EntryInfo[]>([]);

    const loadIdeaList = async () => {
        setIdeaList([]);
        const sessionId = await get_session();
        const res = await request(list_idea({
            session_id: sessionId,
            project_id: props.projectId,
            list_param: {
                filter_by_keyword: false,
                keyword_list: [],
                keyword_search_type: 0,
                filter_by_group_id: false,
                group_id: "",
                filter_by_title_keyword: keyword != "",
                title_keyword: keyword,
            },
            sort_type: 0,
            offset: PAGE_SIZE * curPage,
            limit: PAGE_SIZE,
        }));
        setIdeaList(res.idea_list);
        setTotalCount(res.total_count);
    };

    const loadRequireMentList = async () => {
        setRequireMentList([]);
        const sessionId = await get_session();
        const res = await request(list_requirement({
            session_id: sessionId,
            project_id: props.projectId,
            filter_by_keyword: keyword != "",
            keyword: keyword,
            filter_by_has_link_issue: false,
            has_link_issue: false,
            filter_by_closed: false,
            closed: false,
            filter_by_tag_id_list: false,
            tag_id_list: [],
            filter_by_watch: false,
            offset: PAGE_SIZE * curPage,
            limit: PAGE_SIZE,
            sort_type: 0,
        }));
        setRequireMentList(res.requirement_list);
        setTotalCount(res.total_count);
    };

    const loadIssueList = async (issueType: ISSUE_TYPE) => {
        setIssueList([]);
        const sessionId = await get_session();
        const res = await request(list_issue({
            session_id: sessionId,
            project_id: props.projectId,
            list_param: {
                filter_by_issue_type: true,
                issue_type: issueType,
                filter_by_state: false,
                state_list: [],
                filter_by_create_user_id: false,
                create_user_id_list: [],
                filter_by_assgin_user_id: false,
                assgin_user_id_list: [],
                assgin_user_type: 0,
                filter_by_sprit_id: false,
                sprit_id_list: [],
                filter_by_create_time: false,
                from_create_time: 0,
                to_create_time: 0,
                filter_by_update_time: false,
                from_update_time: 0,
                to_update_time: 0,
                filter_by_title_keyword: keyword != "",
                title_keyword: keyword,
                filter_by_tag_id_list: false,
                tag_id_list: [],
                filter_by_watch: false,
                filter_by_task_priority: false,
                task_priority_list: [],
                filter_by_software_version: false,
                software_version_list: [],
                filter_by_bug_priority: false,
                bug_priority_list: [],
                filter_by_bug_level: false,
                bug_level_list: [],
            },
            sort_type: 0,
            sort_key: 0,
            offset: PAGE_SIZE * curPage,
            limit: PAGE_SIZE,
        }));
        setTotalCount(res.total_count);
        setIssueList(res.info_list);
    };

    const loadTestCaseList = async () => {
        setTestCaseList([]);
        const sessionId = await get_session();
        const res = await request(list_case_flat({
            session_id: sessionId,
            project_id: props.projectId,
            list_param: {
                filter_by_title: keyword != "",
                title: keyword,
                my_watch: false,
            },
            offset: PAGE_SIZE * curPage,
            limit: PAGE_SIZE,
        }));
        setTotalCount(res.count);
        setTestCaseList(res.case_list);
    };

    const loadServerList = async () => {
        setServerList([]);
        const sessionId = await get_session();
        const res = await request(list_server({
            session_id: sessionId,
            project_id: props.projectId,
        }));
        setServerList(res.server_info_list);
    };

    const loadEntryList = async (entryType: ENTRY_TYPE) => {
        setEntryList([]);
        const sessionId = await get_session();
        const res = await request(list_entry({
            session_id: sessionId,
            project_id: props.projectId,
            list_param: {
                filter_by_watch: false,
                filter_by_tag_id: false,
                tag_id_list: [],
                filter_by_keyword: keyword != "",
                keyword: keyword,
                filter_by_entry_type: true,
                entry_type_list: [entryType],
            },
            offset: PAGE_SIZE * curPage,
            limit: PAGE_SIZE,
        }));
        setTotalCount(res.total_count);
        setEntryList(res.entry_list);
    };

    const loadData = async () => {
        if (curTreeNodeType == "idea") {
            loadIdeaList();
        } else if (curTreeNodeType == "requireMent") {
            loadRequireMentList();
        } else if (curTreeNodeType == "task") {
            loadIssueList(ISSUE_TYPE_TASK);
        } else if (curTreeNodeType == "bug") {
            loadIssueList(ISSUE_TYPE_BUG);
        } else if (curTreeNodeType == "testCase") {
            loadTestCaseList();
        } else if (curTreeNodeType == "server") {
            loadServerList();
        } else if (curTreeNodeType == "workPlan") {
            loadEntryList(ENTRY_TYPE_SPRIT);
        } else if (curTreeNodeType == "doc") {
            loadEntryList(ENTRY_TYPE_DOC);
        } else if (curTreeNodeType == "draw") {
            loadEntryList(ENTRY_TYPE_DRAW);
        } else if (curTreeNodeType == "pages") {
            loadEntryList(ENTRY_TYPE_PAGES);
        } else if (curTreeNodeType == "apiColl") {
            loadEntryList(ENTRY_TYPE_API_COLL);
        }
    };

    useEffect(() => {
        loadData();
    }, [curTreeNodeType, curPage, keyword]);

    return (
        <div>
            {expand == false && (
                <Space style={{ cursor: "pointer", backgroundColor: "white", padding: "2px 10px" }} onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    setExpand(true);
                }}>
                    <span style={{ fontSize: "16px" }}>节点库</span>
                    <CaretDownFilled style={{ fontSize: "24px" }} />
                </Space>
            )}
            {expand == true && (
                <Card title="节点库" style={{ width: "250px" }} bodyStyle={{ maxHeight: "80vh", overflowY: "scroll" }}
                    extra={
                        <Space>
                            <TreeSelect value={curTreeNodeType} onChange={value => {
                                setCurPage(0);
                                setTotalCount(0);
                                setKeyword("");
                                setCurTreeNodeType(value);
                            }}
                                style={{ width: "130px" }}
                                treeDefaultExpandAll
                                treeData={[
                                    {
                                        value: "base",
                                        title: "基础节点",
                                    },
                                    {
                                        value: "idea",
                                        title: "知识点",
                                    },
                                    {
                                        value: "requireMent",
                                        title: "项目需求",
                                    },
                                    {
                                        value: "task",
                                        title: "项目任务",
                                    },
                                    {
                                        value: "bug",
                                        title: "项目缺陷",
                                    },
                                    {
                                        value: "testCase",
                                        title: "测试用例",
                                    },
                                    {
                                        value: "server",
                                        title: "服务器",
                                    },
                                    {
                                        value: "entry",
                                        title: "内容入口",

                                        children: [
                                            {
                                                value: "workPlan",
                                                title: "工作计划",
                                            },
                                            {
                                                value: "doc",
                                                title: "项目文档",
                                            },
                                            {
                                                value: "draw",
                                                title: "绘图白板",
                                            },
                                            {
                                                value: "pages",
                                                title: "静态网页",
                                            },
                                            {
                                                value: "file",
                                                title: "文件",
                                            },
                                            {
                                                value: "apiColl",
                                                title: "接口集合",
                                            }
                                        ],
                                    }
                                ]} />
                            <Button type="text" icon={<CaretUpFilled style={{ fontSize: "24px" }} />} onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setExpand(false);
                            }} title='收起' />
                        </Space>
                    }>
                    {curTreeNodeType != "base" && (
                        <Form layout='inline'>
                            <Form.Item label="关键词" style={{ marginRight: "2px" }}>
                                <Input value={keyword} onChange={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    setCurPage(0);
                                    setKeyword(e.target.value.trim());
                                }} disabled={curTreeNodeType == "server"} style={{ width: "130px" }} />
                            </Form.Item>
                            <Form.Item style={{ marginRight: "2px" }}>
                                <Button type="text" icon={<ReloadOutlined />} style={{ minWidth: 0, padding: "0px 0px" }} title='刷新'
                                    onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        loadData();
                                    }} />
                            </Form.Item>
                        </Form>
                    )}

                    {curTreeNodeType == "base" && (
                        <div>
                            <ProjectDragTreeNode title="分组" dragNodeInfo={{
                                nodeType: NODE_TYPE_BASE_GROUP,
                                nodeData: {
                                    BaseGroupName: "分组"
                                },
                                defaultWidth: 500,
                                defaultHeight: 500,
                            }} />
                            <Divider style={{ margin: "10px 0px" }} />
                            <ProjectDragTreeNode title="文本" dragNodeInfo={{
                                nodeType: NODE_TYPE_BASE_TEXT,
                                nodeData: {
                                    BaseText: "文本",
                                },
                                defaultWidth: 200,
                                defaultHeight: 40,
                            }} />
                            <Divider style={{ margin: "10px 0px" }} />
                            <ProjectDragTreeNode title="内嵌网页" dragNodeInfo={{
                                nodeType: NODE_TYPE_BASE_IFRAME,
                                nodeData: {
                                    BaseIframeUrl: "https://www.linksaas.pro",
                                },
                                defaultWidth: 500,
                                defaultHeight: 500,
                            }} />
                            <Divider style={{ margin: "10px 0px" }} />
                            <ProjectDragTreeNode title="空白引用" dragNodeInfo={{
                                nodeType: NODE_TYPE_BASE_EMPTY_REF,
                                nodeData: {
                                    RefTargetId: "",
                                },
                                defaultWidth: 250,
                                defaultHeight: 150,
                            }} />
                        </div>
                    )}

                    {curTreeNodeType == "idea" && (
                        <List rowKey="idea_id" dataSource={ideaList}
                            pagination={{ total: totalCount, current: curPage + 1, pageSize: PAGE_SIZE, onChange: page => setCurPage(page - 1), hideOnSinglePage: true, showSizeChanger: false }}
                            renderItem={item => (
                                <List.Item>
                                    <ProjectDragTreeNode title={item.basic_info.title} dragNodeInfo={{
                                        nodeType: NODE_TYPE_REF_IDEA,
                                        nodeData: {
                                            RefTargetId: item.idea_id,
                                        },
                                        defaultWidth: 200,
                                        defaultHeight: 100,
                                    }} />
                                </List.Item>
                            )} />
                    )}
                    {curTreeNodeType == "requireMent" && (
                        <List rowKey="requirement_id" dataSource={requireMentList}
                            pagination={{ total: totalCount, current: curPage + 1, pageSize: PAGE_SIZE, onChange: page => setCurPage(page - 1), hideOnSinglePage: true, showSizeChanger: false }}
                            renderItem={item => (
                                <List.Item>
                                    <ProjectDragTreeNode title={`${item.base_info.title}(状态:${item.closed ? "关闭" : "打开"})`} dragNodeInfo={{
                                        nodeType: NODE_TYPE_REF_REQUIREMENT,
                                        nodeData: {
                                            RefTargetId: item.requirement_id,
                                        },
                                        defaultWidth: 200,
                                        defaultHeight: 100,
                                    }} />
                                </List.Item>
                            )} />
                    )}
                    {["task", "bug"].includes(curTreeNodeType) && (
                        <List rowKey="issue_id" dataSource={issueList}
                            pagination={{ total: totalCount, current: curPage + 1, pageSize: PAGE_SIZE, onChange: page => setCurPage(page - 1), hideOnSinglePage: true, showSizeChanger: false }}
                            renderItem={item => (
                                <List.Item>
                                    <ProjectDragTreeNode title={`${item.basic_info.title}(状态:${issueState[item.state].label})`} dragNodeInfo={{
                                        nodeType: curTreeNodeType == "task" ? NODE_TYPE_REF_TASK : NODE_TYPE_REF_BUG,
                                        nodeData: {
                                            RefTargetId: item.issue_id,
                                        },
                                        defaultWidth: 200,
                                        defaultHeight: 100,
                                    }} />
                                </List.Item>
                            )} />
                    )}
                    {curTreeNodeType == "testCase" && (
                        <List rowKey="case_id" dataSource={testCaseList}
                            pagination={{ total: totalCount, current: curPage + 1, pageSize: PAGE_SIZE, onChange: page => setCurPage(page - 1), hideOnSinglePage: true, showSizeChanger: false }}
                            renderItem={item => (
                                <List.Item>
                                    <ProjectDragTreeNode title={item.title} dragNodeInfo={{
                                        nodeType: NODE_TYPE_REF_TESTCASE,
                                        nodeData: {
                                            RefTargetId: item.case_id,
                                        },
                                        defaultWidth: 200,
                                        defaultHeight: 100,
                                    }} />
                                </List.Item>
                            )} />
                    )}
                    {curTreeNodeType == "server" && (
                        <List rowKey="server_id" dataSource={serverList}
                            pagination={false}
                            renderItem={item => (
                                <List.Item>
                                    <ProjectDragTreeNode title={item.basic_info.server_name} dragNodeInfo={{
                                        nodeType: NODE_TYPE_REF_SERVER,
                                        nodeData: {
                                            RefTargetId: item.server_id,
                                        },
                                        defaultWidth: 200,
                                        defaultHeight: 80,
                                    }} />
                                </List.Item>
                            )} />
                    )}
                    {["workPlan", "doc", "draw", "pages", "file", "apiColl"].includes(curTreeNodeType) && (
                        <List rowKey="entry_id" dataSource={entryList}
                            pagination={{ total: totalCount, current: curPage + 1, pageSize: PAGE_SIZE, onChange: page => setCurPage(page - 1), hideOnSinglePage: true, showSizeChanger: false }}
                            renderItem={item => (
                                <List.Item>
                                    <ProjectDragTreeNode title={item.entry_title} dragNodeInfo={{
                                        nodeType: NODE_TYPE_REF_ENTRY,
                                        nodeData: {
                                            RefTargetId: item.entry_id,
                                        },
                                        defaultWidth: 200,
                                        defaultHeight: 40,
                                    }} />
                                </List.Item>
                            )} />
                    )}
                </Card>
            )}
        </div>
    );
};

export default ProjectNodeListPanel;